package com.heo.util;

import java.util.Map;
import org.apache.log4j.Logger;
import com.alibaba.fastjson.JSONObject;
import com.heo.pojo.StatusDictEntity;
import com.heo.pub.DictEnum;
import com.heo.task.SendTaskQueuePriority;
import com.heo.task.thread.WaterSendInfo;

import io.netty.channel.ChannelHandlerContext;

public class DeviceServiceUtils {
	
	private static Logger logger = Logger.getLogger(DeviceServiceUtils.class);

	public static void cardRecharge(String appId, String deviceImei, String h, JSONObject paramsMap) throws Exception { 
		if (Utils.checkNull(h)) {
			//int withoutCode, int balances, int score
			int length = h.length();
			if(h.length() > 2){
				String end = h.substring(length-2, length);
				JSONObject rspJsonMap = new  JSONObject();
				if("45".equals(end)){
					String withoutCodeStr = h.substring(2, length-2);
					if(Utils.checkNull(withoutCodeStr)){
						int withoutCode = ByteHelper.hex16ToInt(withoutCodeStr);
						paramsMap.put("withoutCode", withoutCode);
						StringBuilder sBuilder = new StringBuilder("0C66");
						sBuilder.append(ByteHelper.hexIntegerToBytes(withoutCode, 4));
						sBuilder.append("88");
						sBuilder.append(Utils.getInitStr());
						sBuilder.append("99");
						String initTime = sBuilder.toString(); 
						rspJsonMap.put("h", initTime);
						rspJsonMap.put("o", 4);
						WaterSendInfo codeSendInfo = new WaterSendInfo(appId, deviceImei, rspJsonMap.toJSONString(), 1, 2000);
						SendTaskQueuePriority.getInstance().addCallBackMsg(codeSendInfo);
					}
				}else{
					String cmd = h.substring(6, 8);
					int withoutCode = paramsMap.getIntValue("withoutCode");
					//没有机器号，手动去获取机器号
					if(withoutCode == 0) {
						rspJsonMap.put("h", "056600002299");
						rspJsonMap.put("o", 4);
						WaterSendInfo codeSendInfo = new WaterSendInfo(appId, deviceImei, rspJsonMap.toJSONString(), 1, 3000);
						SendTaskQueuePriority.getInstance().addCallBackMsg(codeSendInfo);
					}
					if("66".equals(cmd) && length == 20){
						String cardStr = h.substring(8, 14);
						String balance = h.substring(14, 18);
						String card = ByteHelper.hex16To10Str(cardStr, 5);
						Map<String, Object> balanceMap = NettyChannelMapUtils.queryBalance(card);
						if (balanceMap == null){
							StringBuilder sBuilder = new StringBuilder("0C66");
							sBuilder.append(ByteHelper.hexIntegerToBytes(withoutCode, 4));
							sBuilder.append("55");
							sBuilder.append(cardStr);
							sBuilder.append("0000000000");
							String cmdCode = sBuilder.toString(); 
							rspJsonMap.put("h", cmdCode);
							rspJsonMap.put("o", 4);
							WaterSendInfo codeSendInfo = new WaterSendInfo(appId, deviceImei, rspJsonMap.toJSONString(), 1, 2000);
							SendTaskQueuePriority.getInstance().addCallBackMsg(codeSendInfo);
						}else{
							int balances = Utils.getInteger(balanceMap.get("balance"));
							int score = Utils.getInteger(balanceMap.get("score"));
							int balanceInt = balances + score;
							int status =  Utils.getInteger(balanceMap.get("STATUS"));
							logger.info("机器号：" + withoutCode + "，卡号：" + card + ", 余额：" + Integer.parseInt(balance, 16) + "分，充值金额：" + balanceInt + "分");
							if(balanceInt > 0){
								StringBuilder sBuilder = new StringBuilder("0C66");
								sBuilder.append(ByteHelper.hexIntegerToBytes(withoutCode, 4));
								if(1==status){
									sBuilder.append("66");
									paramsMap.put("balances", balances);
									paramsMap.put("score", score);
								}else{
									sBuilder.append("11");
								}
								sBuilder.append(cardStr);
								sBuilder.append(ByteHelper.hexIntegerToBytes(balanceInt, 4));
								sBuilder.append(ByteHelper.hexIntegerToBytes(balanceInt, 4));
								sBuilder.append(Utils.initRechargeCheck(balance));
								String cmdCode = sBuilder.toString(); 
								rspJsonMap.put("h", cmdCode);
								rspJsonMap.put("o", 4);
								WaterSendInfo codeSendInfo = new WaterSendInfo(appId, deviceImei, rspJsonMap.toJSONString(), 1, 2000);
								SendTaskQueuePriority.getInstance().addCallBackMsg(codeSendInfo);
							}
						}
					}else if("33".equals(cmd) && length == 20){
						String cardStr = h.substring(8, 14);
						String card = ByteHelper.hex16To10Str(cardStr, 5);
						int balances = paramsMap.getIntValue("balances");
						int score = paramsMap.getIntValue("score");
						NettyChannelMapUtils.balanceSuccess(card, balances, score);
						paramsMap.remove("balances");
						paramsMap.remove("score");
					}
				}
			}
		}
	}
	
	public static void aiyaxingChargingPile(String appId, String deviceImei, String cmd, String callUrl, Map<String, StatusDictEntity> statusDictMap, ChannelHandlerContext mCtx) {
		if(cmd.startsWith("02")) {
			int deviceChannelId = Utils.getInt(cmd.substring(2, 4));
			//通道从0开始
			deviceChannelId = deviceChannelId - 1;
			String code = cmd.substring(4, 6);
			if("01".equals(code)) {
				cmd = "00";
				NettyChannelMapUtils.callBackSendStatus(appId, deviceImei, deviceChannelId,
						DictEnum.CallBackType.STATUS_REPORT, cmd, callUrl, statusDictMap, mCtx);
			}
		}else if(cmd.startsWith("05")) {
			int deviceChannelId = Utils.getInt(cmd.substring(2, 4));
			//通道从0开始
			deviceChannelId = deviceChannelId - 1;
			String code = cmd.substring(4, 6);
			if(code.equals("00") || code.equals("01") || code.equals("02")) {
				cmd = "01";
				NettyChannelMapUtils.callBackSendStatus(appId, deviceImei, deviceChannelId,
							DictEnum.CallBackType.STATUS_REPORT, cmd, callUrl, statusDictMap, mCtx);
			}else {
				cmd = "04";
				NettyChannelMapUtils.callBackSendStatus(appId, deviceImei, deviceChannelId,
						DictEnum.CallBackType.STATUS_REPORT, cmd, callUrl, statusDictMap, mCtx);
			}
			
		}else if(cmd.startsWith("01")) {
			String code = cmd.substring(2);
			int length = code.length() / 2;
			for(int i =0; i < length; i++) {
				int start = i*2;
				String st = code.substring(start, start + 2);
				if(st.equals("01")) {
					cmd = "01";
					NettyChannelMapUtils.callBackSendStatus(appId, deviceImei, i,
							DictEnum.CallBackType.STATUS_REPORT, cmd, callUrl, statusDictMap, mCtx);
				}else if(st.equals("02")) {
					cmd = "00";
					NettyChannelMapUtils.callBackSendStatus(appId, deviceImei, i,
							DictEnum.CallBackType.STATUS_REPORT, cmd, callUrl, statusDictMap, mCtx);
				}else {
					cmd = st;
					NettyChannelMapUtils.callBackSendStatusError(appId, deviceImei, i,
							DictEnum.CallBackType.STATUS_REPORT, cmd, callUrl, statusDictMap, mCtx);
				}
			}
		}
	}
}
